// src/screenshot-service.ts
import { Page } from 'playwright';
import { WebSocket } from 'ws';

// 截图并发送给 WebSocket 客户端
export async function sendScreenshot(page: Page, ws: WebSocket) {
  try {
    const buffer = await page.screenshot({
      type: 'jpeg',
      quality: 60, // 降低质量以减小体积
      timeout: 5000
    });
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(buffer); // 发送二进制图像
    }
  } catch (e) {
    console.warn('Screenshot failed:', e);
  }
}

// 启动定时截图推送
export function startStreaming(page: Page, ws: WebSocket, intervalMs: number = 500) {
  const timer = setInterval(() => {
    sendScreenshot(page, ws);
  }, intervalMs);

  // 清理
  ws.on('close', () => clearInterval(timer));
  ws.on('error', () => clearInterval(timer));

  // 首帧立即发送
  sendScreenshot(page, ws);

  return timer;
}